using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using WL.Think.Abp.EntityFrameworkCore;

namespace WL.Think.Abp;

public abstract class ThinkDbMigratorDbContextFactory<TDbContext> : IDesignTimeDbContextFactory<TDbContext> where TDbContext : AppDbContextBase<TDbContext>
{
    public TDbContext CreateDbContext(string[] args)
    {
        AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

        var configuration = BuildConfiguration();
        var builder = new DbContextOptionsBuilder<TDbContext>();

        ConfigureDbContextOptionsBuilder(builder, configuration);

        return (TDbContext)Activator.CreateInstance(typeof(TDbContext), builder.Options)!;
    }

    protected abstract void ConfigureDbContextOptionsBuilder(DbContextOptionsBuilder<TDbContext> builder, IConfigurationRoot configuration);

    private IConfigurationRoot BuildConfiguration()
    {
        var options = new AbpConfigurationBuilderOptions
        {
            EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
        };

        var configuration = ConfigurationHelper.BuildConfiguration(options);
        return configuration;
    }
}
